package com.github.bluesbruce.websocket;

import java.security.Principal;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

/**
 * 消息头拦截器，获取用户认证信息
 * <p>如果没有这个配置，SimpUserRegistry就无法统计在线人数</p>
 *
 * @author BBF
 */
public class MyPrincipalHandshakeHandler extends DefaultHandshakeHandler {

  private static final Logger LOGGER = LoggerFactory.getLogger(MyPrincipalHandshakeHandler.class);

  @Override
  protected Principal determineUser(ServerHttpRequest request,
      WebSocketHandler wsHandler, Map<String, Object> attributes) {
    HttpSession httpSession = getSession(request);
    // 获取登录的信息
    String user = (String) httpSession.getAttribute("loginName");

    if (StringUtils.isEmpty(user)) {
      LOGGER.error("未登录系统，禁止使用WebSocket!");
      return null;
    }
    LOGGER.info(" MyDefaultHandshakeHandler login = {}", user);
    return new WebSocketUserAuthentication(user);
  }

  private HttpSession getSession(ServerHttpRequest request) {
    if (request instanceof ServletServerHttpRequest) {
      ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
      return serverRequest.getServletRequest().getSession(false);
    }
    return null;
  }

}